import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';

// JWT 密钥 - 在生产环境中应该从环境变量获取
const JWT_SECRET = process.env.JWT_SECRET || 'your-super-secret-jwt-key-change-in-production';
const JWT_EXPIRES_IN = '24h';

// 用户接口定义
export interface User {
  id: string;
  username: string;
  email: string;
  password: string;
  createdAt: Date;
}

// 登录请求接口
export interface LoginRequest {
  username: string;
  password: string;
}

// 注册请求接口
export interface RegisterRequest {
  username: string;
  email: string;
  password: string;
}

// JWT 载荷接口
export interface JWTPayload {
  userId: string;
  username: string;
  email: string;
}

// 内存存储用户数据（生产环境应使用数据库）
const users: User[] = [
  {
    id: '1',
    username: 'admin',
    email: 'admin@example.com',
    password: '$2a$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
    createdAt: new Date()
  }
];

// 生成 JWT Token
export function generateToken(payload: JWTPayload): string {
  return jwt.sign(payload, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN });
}

// 验证 JWT Token
export function verifyToken(token: string): JWTPayload | null {
  try {
    return jwt.verify(token, JWT_SECRET) as JWTPayload;
  } catch (error) {
    console.error('Token 验证失败:', error);
    return null;
  }
}

// 密码加密
export async function hashPassword(password: string): Promise<string> {
  const saltRounds = 10;
  return await bcrypt.hash(password, saltRounds);
}

// 验证密码
export async function verifyPassword(password: string, hashedPassword: string): Promise<boolean> {
  return await bcrypt.compare(password, hashedPassword);
}

// 用户注册
export async function registerUser(userData: RegisterRequest): Promise<{ success: boolean; message: string; user?: Partial<User> }> {
  try {
    // 检查用户名是否已存在
    const existingUser = users.find(u => u.username === userData.username || u.email === userData.email);
    if (existingUser) {
      return {
        success: false,
        message: '用户名或邮箱已存在'
      };
    }

    // 加密密码
    const hashedPassword = await hashPassword(userData.password);

    // 创建新用户
    const newUser: User = {
      id: (users.length + 1).toString(),
      username: userData.username,
      email: userData.email,
      password: hashedPassword,
      createdAt: new Date()
    };

    users.push(newUser);

    // 返回用户信息（不包含密码）
    const { password, ...userWithoutPassword } = newUser;

    return {
      success: true,
      message: '注册成功',
      user: userWithoutPassword
    };
  } catch (error) {
    console.error('注册失败:', error);
    return {
      success: false,
      message: '注册失败，请稍后重试'
    };
  }
}

// 用户登录
export async function loginUser(loginData: LoginRequest): Promise<{ success: boolean; message: string; token?: string; user?: Partial<User> }> {
  try {
    // 查找用户
    const user = users.find(u => u.username === loginData.username);
    if (!user) {
      return {
        success: false,
        message: '用户名或密码错误'
      };
    }

    // 验证密码
    const isValidPassword = await verifyPassword(loginData.password, user.password);
    if (!isValidPassword) {
      return {
        success: false,
        message: '用户名或密码错误'
      };
    }

    // 生成 JWT Token
    const payload: JWTPayload = {
      userId: user.id,
      username: user.username,
      email: user.email
    };
    const token = generateToken(payload);

    // 返回用户信息（不包含密码）
    const { password, ...userWithoutPassword } = user;

    return {
      success: true,
      message: '登录成功',
      token,
      user: userWithoutPassword
    };
  } catch (error) {
    console.error('登录失败:', error);
    return {
      success: false,
      message: '登录失败，请稍后重试'
    };
  }
}

// 根据用户ID获取用户信息
export function getUserById(userId: string): Partial<User> | null {
  const user = users.find(u => u.id === userId);
  if (!user) {
    return null;
  }
  
  const { password, ...userWithoutPassword } = user;
  return userWithoutPassword;
}

// 验证中间件
export function authenticateToken(req: Request): { isValid: boolean; user?: Partial<User>; error?: string } {
  try {
    const authHeader = req.headers.get('authorization');
    const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN

    if (!token) {
      return {
        isValid: false,
        error: '缺少访问令牌'
      };
    }

    const payload = verifyToken(token);
    if (!payload) {
      return {
        isValid: false,
        error: '无效的访问令牌'
      };
    }

    const user = getUserById(payload.userId);
    if (!user) {
      return {
        isValid: false,
        error: '用户不存在'
      };
    }

    return {
      isValid: true,
      user
    };
  } catch (error) {
    console.error('认证中间件错误:', error);
    return {
      isValid: false,
      error: '认证失败'
    };
  }
}

// 获取所有用户（管理员功能）
export function getAllUsers(): Partial<User>[] {
  return users.map(user => {
    const { password, ...userWithoutPassword } = user;
    return userWithoutPassword;
  });
}
